package com.kb.controller;

import com.kb.common.ApiResponse;
import com.kb.domain.Bom;
import com.kb.domain.BomRfqDetail;
import com.kb.domain.RepurchaseOrder;
import com.kb.service.common.CommonService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Resource
    private CommonService commonService;

    /**
     * 根据机型获取复投单
     */
    @GetMapping("/getRepurchaseOrder")
    public ApiResponse<List<RepurchaseOrder>> getRepurchaseOrder(
            @RequestParam(value = "Part_No") String Part_No) {
        return ApiResponse.success(commonService.getRepurchaseOrder(Part_No));
    }

    /**
     * 根据BOM编号获取明细
     */
    @GetMapping("/getBomDetail/{rfqNo}")
    public ApiResponse<List<BomRfqDetail>> getBomDetail(
            @PathVariable("rfqNo") String rfqNo) {
        return ApiResponse.success(commonService.getBomDetail(rfqNo));
    }
    /**
     * 根据RFQ号获取BOM主表及明细
     */
    @GetMapping("/getBomContent/{rfqNo}")
    public ApiResponse<Bom> getBomContent(
            @PathVariable("rfqNo") String rfqNo) {
        return ApiResponse.success(commonService.getBomContent(rfqNo));
    }



    /**
     * 根据BOM编号获取文件
     */
    @GetMapping("/getBomFile/{rfqNo}")
    @ResponseBody
    public ResponseEntity<byte[]> getFileFromLAN(@PathVariable("rfqNo") String rfqNo) throws IOException {
        String bomFile = commonService.getBomFile(rfqNo);
        if (bomFile == null) {
            throw new RuntimeException("文件不存在");
        }
        //判断bomFile的字段值是否以~开头，如果是则补充bomFile字段值
//      http://192.168.10.22:7055/Content/uploadFiles/BM25073122905/OriginalFile/PCB-000876%20Rev%204%20Deliverables%20PX%20Control%20Board%2020250724.xlsx
        if (bomFile.startsWith("http")) {
            bomFile = bomFile;
        } else if (bomFile.startsWith("~")) {
            bomFile = bomFile.replace("~", "http://192.168.10.22:7055/");
        }
        try {
            // 使用 RestTemplate 下载文件
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<byte[]> response = restTemplate.getForEntity(bomFile, byte[].class);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                byte[] fileBytes = response.getBody();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

                // 从URL中提取文件名
                String filename = "downloaded_file.xlsx";
                if (bomFile.contains("/")) {
                    filename = bomFile.substring(bomFile.lastIndexOf("/") + 1);
                }

                headers.setContentDispositionFormData("attachment", filename);
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(fileBytes);
            }
        } catch (Exception e) {
            System.err.println("下载文件失败: " + e.getMessage());
            throw new RuntimeException("文件下载失败", e);
        }

        return ResponseEntity.notFound().build();
    }


}